

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>nlp_architect.nn.torch.layers.crf &mdash; NLP Architect by Intel® AI Lab 0.5.2 documentation</title>
  

  
  
  
  

  
  <script type="text/javascript" src="../../../../../_static/js/modernizr.min.js"></script>
  
    
      <script type="text/javascript" id="documentation_options" data-url_root="../../../../../" src="../../../../../_static/documentation_options.js"></script>
        <script type="text/javascript" src="../../../../../_static/jquery.js"></script>
        <script type="text/javascript" src="../../../../../_static/underscore.js"></script>
        <script type="text/javascript" src="../../../../../_static/doctools.js"></script>
        <script type="text/javascript" src="../../../../../_static/language_data.js"></script>
        <script type="text/javascript" src="../../../../../_static/install.js"></script>
        <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
    
    <script type="text/javascript" src="../../../../../_static/js/theme.js"></script>

    

  
  <link rel="stylesheet" href="../../../../../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../../../../../_static/pygments.css" type="text/css" />
  <link rel="stylesheet" href="../../../../../_static/nlp_arch_theme.css" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono" type="text/css" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:100,900" type="text/css" />
    <link rel="index" title="Index" href="../../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../../search.html" /> 
</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">
    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search" >
          

          
            <a href="../../../../../index.html">
          

          
            
            <img src="../../../../../_static/logo.png" class="logo" alt="Logo"/>
          
          </a>

          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../../../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../../quick_start.html">Quick start</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../installation.html">Installation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../publications.html">Publications</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../tutorials.html">Jupyter Tutorials</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../model_zoo.html">Model Zoo</a></li>
</ul>
<p class="caption"><span class="caption-text">NLP/NLU Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../../tagging/sequence_tagging.html">Sequence Tagging</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../sentiment.html">Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../bist_parser.html">Dependency Parsing</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../intent.html">Intent Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../lm.html">Language Models</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../information_extraction.html">Information Extraction</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../transformers.html">Transformers</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../archived/additional.html">Additional Models</a></li>
</ul>
<p class="caption"><span class="caption-text">Optimized Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../../quantized_bert.html">Quantized BERT</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../transformers_distillation.html">Transformers Distillation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../sparse_gnmt.html">Sparse Neural Machine Translation</a></li>
</ul>
<p class="caption"><span class="caption-text">Solutions</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../../absa_solution.html">Aspect Based Sentiment Analysis</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../term_set_expansion.html">Set Expansion</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../trend_analysis.html">Trend Analysis</a></li>
</ul>
<p class="caption"><span class="caption-text">For Developers</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../../../../../generated_api/nlp_architect_api_index.html">nlp_architect API</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../../../../developer_guide.html">Developer Guide</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../../../../../index.html">NLP Architect by Intel® AI Lab</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../../../../../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../../../../index.html">Module code</a> &raquo;</li>
        
          <li><a href="../../torch.html">nlp_architect.nn.torch</a> &raquo;</li>
        
      <li>nlp_architect.nn.torch.layers.crf</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <h1>Source code for nlp_architect.nn.torch.layers.crf</h1><div class="highlight"><pre>
<span></span><span class="c1"># ******************************************************************************</span>
<span class="c1"># Copyright 2017-2019 Intel Corporation</span>
<span class="c1">#</span>
<span class="c1"># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span>
<span class="c1"># you may not use this file except in compliance with the License.</span>
<span class="c1"># You may obtain a copy of the License at</span>
<span class="c1">#</span>
<span class="c1">#     http://www.apache.org/licenses/LICENSE-2.0</span>
<span class="c1">#</span>
<span class="c1"># Unless required by applicable law or agreed to in writing, software</span>
<span class="c1"># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span>
<span class="c1"># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
<span class="c1"># See the License for the specific language governing permissions and</span>
<span class="c1"># limitations under the License.</span>
<span class="c1"># ******************************************************************************</span>
<span class="c1"># Module adapted from https://github.com/kmkurn/pytorch-crf</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span><span class="p">,</span> <span class="n">Optional</span>

<span class="kn">import</span> <span class="nn">torch</span>
<span class="kn">import</span> <span class="nn">torch.nn</span> <span class="k">as</span> <span class="nn">nn</span>


<div class="viewcode-block" id="CRF"><a class="viewcode-back" href="../../../../../generated_api/nlp_architect.nn.torch.layers.html#nlp_architect.nn.torch.layers.crf.CRF">[docs]</a><span class="k">class</span> <span class="nc">CRF</span><span class="p">(</span><span class="n">nn</span><span class="o">.</span><span class="n">Module</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Conditional random field.</span>
<span class="sd">    This module implements a conditional random field [LMP01]_. The forward computation</span>
<span class="sd">    of this class computes the log likelihood of the given sequence of tags and</span>
<span class="sd">    emission score tensor. This class also has `~CRF.decode` method which finds</span>
<span class="sd">    the best tag sequence given an emission score tensor using `Viterbi algorithm`_.</span>
<span class="sd">    Args:</span>
<span class="sd">        num_tags: Number of tags.</span>
<span class="sd">        batch_first: Whether the first dimension corresponds to the size of a minibatch.</span>
<span class="sd">    Attributes:</span>
<span class="sd">        start_transitions (`~torch.nn.Parameter`): Start transition score tensor of size</span>
<span class="sd">            ``(num_tags,)``.</span>
<span class="sd">        end_transitions (`~torch.nn.Parameter`): End transition score tensor of size</span>
<span class="sd">            ``(num_tags,)``.</span>
<span class="sd">        transitions (`~torch.nn.Parameter`): Transition score tensor of size</span>
<span class="sd">            ``(num_tags, num_tags)``.</span>
<span class="sd">    .. [LMP01] Lafferty, J., McCallum, A., Pereira, F. (2001).</span>
<span class="sd">       &quot;Conditional random fields: Probabilistic models for segmenting and</span>
<span class="sd">       labeling sequence data&quot;. *Proc. 18th International Conf. on Machine</span>
<span class="sd">       Learning*. Morgan Kaufmann. pp. 282–289.</span>
<span class="sd">    .. _Viterbi algorithm: https://en.wikipedia.org/wiki/Viterbi_algorithm</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">num_tags</span><span class="p">:</span> <span class="nb">int</span><span class="p">,</span> <span class="n">batch_first</span><span class="p">:</span> <span class="nb">bool</span> <span class="o">=</span> <span class="kc">False</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">num_tags</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;invalid number of tags: </span><span class="si">{num_tags}</span><span class="s2">&quot;</span><span class="p">)</span>
        <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">num_tags</span> <span class="o">=</span> <span class="n">num_tags</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">batch_first</span> <span class="o">=</span> <span class="n">batch_first</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">start_transitions</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">empty</span><span class="p">(</span><span class="n">num_tags</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">end_transitions</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">empty</span><span class="p">(</span><span class="n">num_tags</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">transitions</span> <span class="o">=</span> <span class="n">nn</span><span class="o">.</span><span class="n">Parameter</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">empty</span><span class="p">(</span><span class="n">num_tags</span><span class="p">,</span> <span class="n">num_tags</span><span class="p">))</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">reset_parameters</span><span class="p">()</span>

<div class="viewcode-block" id="CRF.reset_parameters"><a class="viewcode-back" href="../../../../../generated_api/nlp_architect.nn.torch.layers.html#nlp_architect.nn.torch.layers.crf.CRF.reset_parameters">[docs]</a>    <span class="k">def</span> <span class="nf">reset_parameters</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="kc">None</span><span class="p">:</span>
        <span class="sd">&quot;&quot;&quot;Initialize the transition parameters.</span>
<span class="sd">        The parameters will be initialized randomly from a uniform distribution</span>
<span class="sd">        between -0.1 and 0.1.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">nn</span><span class="o">.</span><span class="n">init</span><span class="o">.</span><span class="n">uniform_</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">start_transitions</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">)</span>
        <span class="n">nn</span><span class="o">.</span><span class="n">init</span><span class="o">.</span><span class="n">uniform_</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">end_transitions</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">)</span>
        <span class="n">nn</span><span class="o">.</span><span class="n">init</span><span class="o">.</span><span class="n">uniform_</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">transitions</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">)</span></div>

    <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
        <span class="k">return</span> <span class="sa">f</span><span class="s2">&quot;</span><span class="si">{self.__class__.__name__}</span><span class="s2">(num_tags=</span><span class="si">{self.num_tags}</span><span class="s2">)&quot;</span>

<div class="viewcode-block" id="CRF.forward"><a class="viewcode-back" href="../../../../../generated_api/nlp_architect.nn.torch.layers.html#nlp_architect.nn.torch.layers.crf.CRF.forward">[docs]</a>    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">emissions</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span>
        <span class="n">tags</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">LongTensor</span><span class="p">,</span>
        <span class="n">mask</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">torch</span><span class="o">.</span><span class="n">ByteTensor</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">reduction</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s2">&quot;sum&quot;</span><span class="p">,</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span>
        <span class="sd">&quot;&quot;&quot;Compute the conditional log likelihood of a sequence of tags given emission scores.</span>
<span class="sd">        Args:</span>
<span class="sd">            emissions (`~torch.Tensor`): Emission score tensor of size</span>
<span class="sd">                ``(seq_length, batch_size, num_tags)`` if ``batch_first`` is ``False``,</span>
<span class="sd">                ``(batch_size, seq_length, num_tags)`` otherwise.</span>
<span class="sd">            tags (`~torch.LongTensor`): Sequence of tags tensor of size</span>
<span class="sd">                ``(seq_length, batch_size)`` if ``batch_first`` is ``False``,</span>
<span class="sd">                ``(batch_size, seq_length)`` otherwise.</span>
<span class="sd">            mask (`~torch.ByteTensor`): Mask tensor of size ``(seq_length, batch_size)``</span>
<span class="sd">                if ``batch_first`` is ``False``, ``(batch_size, seq_length)`` otherwise.</span>
<span class="sd">            reduction: Specifies  the reduction to apply to the output:</span>
<span class="sd">                ``none|sum|mean|token_mean``. ``none``: no reduction will be applied.</span>
<span class="sd">                ``sum``: the output will be summed over batches. ``mean``: the output will be</span>
<span class="sd">                averaged over batches. ``token_mean``: the output will be averaged over tokens.</span>
<span class="sd">        Returns:</span>
<span class="sd">            `~torch.Tensor`: The log likelihood. This will have size ``(batch_size,)`` if</span>
<span class="sd">            reduction is ``none``, ``()`` otherwise.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_validate</span><span class="p">(</span><span class="n">emissions</span><span class="p">,</span> <span class="n">tags</span><span class="o">=</span><span class="n">tags</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">reduction</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">&quot;none&quot;</span><span class="p">,</span> <span class="s2">&quot;sum&quot;</span><span class="p">,</span> <span class="s2">&quot;mean&quot;</span><span class="p">,</span> <span class="s2">&quot;token_mean&quot;</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;invalid reduction: </span><span class="si">{reduction}</span><span class="s2">&quot;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">mask</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">mask</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">ones_like</span><span class="p">(</span><span class="n">tags</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>

        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_first</span><span class="p">:</span>
            <span class="n">emissions</span> <span class="o">=</span> <span class="n">emissions</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
            <span class="n">tags</span> <span class="o">=</span> <span class="n">tags</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
            <span class="n">mask</span> <span class="o">=</span> <span class="n">mask</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>

        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">numerator</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_compute_score</span><span class="p">(</span><span class="n">emissions</span><span class="p">,</span> <span class="n">tags</span><span class="p">,</span> <span class="n">mask</span><span class="p">)</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">denominator</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_compute_normalizer</span><span class="p">(</span><span class="n">emissions</span><span class="p">,</span> <span class="n">mask</span><span class="p">)</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">llh</span> <span class="o">=</span> <span class="n">numerator</span> <span class="o">-</span> <span class="n">denominator</span>

        <span class="k">if</span> <span class="n">reduction</span> <span class="o">==</span> <span class="s2">&quot;none&quot;</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">llh</span>
        <span class="k">if</span> <span class="n">reduction</span> <span class="o">==</span> <span class="s2">&quot;sum&quot;</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">llh</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">reduction</span> <span class="o">==</span> <span class="s2">&quot;mean&quot;</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">llh</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span>
        <span class="k">assert</span> <span class="n">reduction</span> <span class="o">==</span> <span class="s2">&quot;token_mean&quot;</span>
        <span class="k">return</span> <span class="n">llh</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span> <span class="o">/</span> <span class="n">mask</span><span class="o">.</span><span class="n">float</span><span class="p">()</span><span class="o">.</span><span class="n">sum</span><span class="p">()</span></div>

<div class="viewcode-block" id="CRF.decode"><a class="viewcode-back" href="../../../../../generated_api/nlp_architect.nn.torch.layers.html#nlp_architect.nn.torch.layers.crf.CRF.decode">[docs]</a>    <span class="k">def</span> <span class="nf">decode</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span> <span class="n">emissions</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span> <span class="n">mask</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">torch</span><span class="o">.</span><span class="n">ByteTensor</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="n">List</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">]]:</span>
        <span class="sd">&quot;&quot;&quot;Find the most likely tag sequence using Viterbi algorithm.</span>
<span class="sd">        Args:</span>
<span class="sd">            emissions (`~torch.Tensor`): Emission score tensor of size</span>
<span class="sd">                ``(seq_length, batch_size, num_tags)`` if ``batch_first`` is ``False``,</span>
<span class="sd">                ``(batch_size, seq_length, num_tags)`` otherwise.</span>
<span class="sd">            mask (`~torch.ByteTensor`): Mask tensor of size ``(seq_length, batch_size)``</span>
<span class="sd">                if ``batch_first`` is ``False``, ``(batch_size, seq_length)`` otherwise.</span>
<span class="sd">        Returns:</span>
<span class="sd">            List of list containing the best tag sequence for each batch.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_validate</span><span class="p">(</span><span class="n">emissions</span><span class="p">,</span> <span class="n">mask</span><span class="o">=</span><span class="n">mask</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">mask</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">mask</span> <span class="o">=</span> <span class="n">emissions</span><span class="o">.</span><span class="n">new_ones</span><span class="p">(</span><span class="n">emissions</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>

        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_first</span><span class="p">:</span>
            <span class="n">emissions</span> <span class="o">=</span> <span class="n">emissions</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
            <span class="n">mask</span> <span class="o">=</span> <span class="n">mask</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>

        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_viterbi_decode</span><span class="p">(</span><span class="n">emissions</span><span class="p">,</span> <span class="n">mask</span><span class="p">)</span></div>

    <span class="k">def</span> <span class="nf">_validate</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span>
        <span class="n">emissions</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span>
        <span class="n">tags</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">torch</span><span class="o">.</span><span class="n">LongTensor</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
        <span class="n">mask</span><span class="p">:</span> <span class="n">Optional</span><span class="p">[</span><span class="n">torch</span><span class="o">.</span><span class="n">ByteTensor</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">emissions</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">!=</span> <span class="mi">3</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="sa">f</span><span class="s2">&quot;emissions must have dimension of 3, got {emissions.dim()}&quot;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">emissions</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_tags</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
                <span class="sa">f</span><span class="s2">&quot;expected last dimension of emissions is </span><span class="si">{self.num_tags}</span><span class="s2">, &quot;</span>
                <span class="sa">f</span><span class="s2">&quot;got {emissions.size(2)}&quot;</span>
            <span class="p">)</span>

        <span class="k">if</span> <span class="n">tags</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">emissions</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">!=</span> <span class="n">tags</span><span class="o">.</span><span class="n">shape</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
                    <span class="s2">&quot;the first two dimensions of emissions and tags must match, &quot;</span>
                    <span class="sa">f</span><span class="s2">&quot;got {tuple(emissions.shape[:2])} and {tuple(tags.shape)}&quot;</span>
                <span class="p">)</span>

        <span class="k">if</span> <span class="n">mask</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">emissions</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">!=</span> <span class="n">mask</span><span class="o">.</span><span class="n">shape</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
                    <span class="s2">&quot;the first two dimensions of emissions and mask must match, &quot;</span>
                    <span class="sa">f</span><span class="s2">&quot;got {tuple(emissions.shape[:2])} and {tuple(mask.shape)}&quot;</span>
                <span class="p">)</span>
            <span class="n">no_empty_seq</span> <span class="o">=</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_first</span> <span class="ow">and</span> <span class="n">mask</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
            <span class="n">no_empty_seq_bf</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_first</span> <span class="ow">and</span> <span class="n">mask</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">no_empty_seq</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">no_empty_seq_bf</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;mask of the first timestep must all be on&quot;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_compute_score</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span> <span class="n">emissions</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span> <span class="n">tags</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">LongTensor</span><span class="p">,</span> <span class="n">mask</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">ByteTensor</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span>
        <span class="c1"># emissions: (seq_length, batch_size, num_tags)</span>
        <span class="c1"># tags: (seq_length, batch_size)</span>
        <span class="c1"># mask: (seq_length, batch_size)</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">==</span> <span class="mi">3</span> <span class="ow">and</span> <span class="n">tags</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">==</span> <span class="mi">2</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="n">tags</span><span class="o">.</span><span class="n">shape</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_tags</span>
        <span class="k">assert</span> <span class="n">mask</span><span class="o">.</span><span class="n">shape</span> <span class="o">==</span> <span class="n">tags</span><span class="o">.</span><span class="n">shape</span>
        <span class="k">assert</span> <span class="n">mask</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>

        <span class="n">seq_length</span><span class="p">,</span> <span class="n">batch_size</span> <span class="o">=</span> <span class="n">tags</span><span class="o">.</span><span class="n">shape</span>
        <span class="n">mask</span> <span class="o">=</span> <span class="n">mask</span><span class="o">.</span><span class="n">float</span><span class="p">()</span>

        <span class="c1"># Start transition score and first emission</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">score</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start_transitions</span><span class="p">[</span><span class="n">tags</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span>
        <span class="n">score</span> <span class="o">+=</span> <span class="n">emissions</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="n">torch</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">batch_size</span><span class="p">),</span> <span class="n">tags</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span>

        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">seq_length</span><span class="p">):</span>
            <span class="c1"># Transition score to next tag, only added if next timestep is valid (mask == 1)</span>
            <span class="c1"># shape: (batch_size,)</span>
            <span class="n">score</span> <span class="o">+=</span> <span class="bp">self</span><span class="o">.</span><span class="n">transitions</span><span class="p">[</span><span class="n">tags</span><span class="p">[</span><span class="n">i</span> <span class="o">-</span> <span class="mi">1</span><span class="p">],</span> <span class="n">tags</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span> <span class="o">*</span> <span class="n">mask</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>

            <span class="c1"># Emission score for next tag, only added if next timestep is valid (mask == 1)</span>
            <span class="c1"># shape: (batch_size,)</span>
            <span class="n">score</span> <span class="o">+=</span> <span class="n">emissions</span><span class="p">[</span><span class="n">i</span><span class="p">,</span> <span class="n">torch</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">batch_size</span><span class="p">),</span> <span class="n">tags</span><span class="p">[</span><span class="n">i</span><span class="p">]]</span> <span class="o">*</span> <span class="n">mask</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>

        <span class="c1"># End transition score</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">seq_ends</span> <span class="o">=</span> <span class="n">mask</span><span class="o">.</span><span class="n">long</span><span class="p">()</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">last_tags</span> <span class="o">=</span> <span class="n">tags</span><span class="p">[</span><span class="n">seq_ends</span><span class="p">,</span> <span class="n">torch</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="n">batch_size</span><span class="p">)]</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">score</span> <span class="o">+=</span> <span class="bp">self</span><span class="o">.</span><span class="n">end_transitions</span><span class="p">[</span><span class="n">last_tags</span><span class="p">]</span>

        <span class="k">return</span> <span class="n">score</span>

    <span class="k">def</span> <span class="nf">_compute_normalizer</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">emissions</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span> <span class="n">mask</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">ByteTensor</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">torch</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span>
        <span class="c1"># emissions: (seq_length, batch_size, num_tags)</span>
        <span class="c1"># mask: (seq_length, batch_size)</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">==</span> <span class="mi">3</span> <span class="ow">and</span> <span class="n">mask</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">==</span> <span class="mi">2</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="n">mask</span><span class="o">.</span><span class="n">shape</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_tags</span>
        <span class="k">assert</span> <span class="n">mask</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>

        <span class="n">seq_length</span> <span class="o">=</span> <span class="n">emissions</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>

        <span class="c1"># Start transition score and first emission; score has size of</span>
        <span class="c1"># (batch_size, num_tags) where for each batch, the j-th column stores</span>
        <span class="c1"># the score that the first timestep has tag j</span>
        <span class="c1"># shape: (batch_size, num_tags)</span>
        <span class="n">score</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start_transitions</span> <span class="o">+</span> <span class="n">emissions</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>

        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">seq_length</span><span class="p">):</span>
            <span class="c1"># Broadcast score for every possible next tag</span>
            <span class="c1"># shape: (batch_size, num_tags, 1)</span>
            <span class="n">broadcast_score</span> <span class="o">=</span> <span class="n">score</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

            <span class="c1"># Broadcast emission score for every possible current tag</span>
            <span class="c1"># shape: (batch_size, 1, num_tags)</span>
            <span class="n">broadcast_emissions</span> <span class="o">=</span> <span class="n">emissions</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

            <span class="c1"># Compute the score tensor of size (batch_size, num_tags, num_tags) where</span>
            <span class="c1"># for each sample, entry at row i and column j stores the sum of scores of all</span>
            <span class="c1"># possible tag sequences so far that end with transitioning from tag i to tag j</span>
            <span class="c1"># and emitting</span>
            <span class="c1"># shape: (batch_size, num_tags, num_tags)</span>
            <span class="n">next_score</span> <span class="o">=</span> <span class="n">broadcast_score</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">transitions</span> <span class="o">+</span> <span class="n">broadcast_emissions</span>

            <span class="c1"># Sum over all possible current tags, but we&#39;re in score space, so a sum</span>
            <span class="c1"># becomes a log-sum-exp: for each sample, entry i stores the sum of scores of</span>
            <span class="c1"># all possible tag sequences so far, that end in tag i</span>
            <span class="c1"># shape: (batch_size, num_tags)</span>
            <span class="n">next_score</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">logsumexp</span><span class="p">(</span><span class="n">next_score</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

            <span class="c1"># Set score to the next score if this timestep is valid (mask == 1)</span>
            <span class="c1"># shape: (batch_size, num_tags)</span>
            <span class="n">score</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">mask</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">next_score</span><span class="p">,</span> <span class="n">score</span><span class="p">)</span>

        <span class="c1"># End transition score</span>
        <span class="c1"># shape: (batch_size, num_tags)</span>
        <span class="n">score</span> <span class="o">+=</span> <span class="bp">self</span><span class="o">.</span><span class="n">end_transitions</span>

        <span class="c1"># Sum (log-sum-exp) over all possible tags</span>
        <span class="c1"># shape: (batch_size,)</span>
        <span class="k">return</span> <span class="n">torch</span><span class="o">.</span><span class="n">logsumexp</span><span class="p">(</span><span class="n">score</span><span class="p">,</span> <span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">_viterbi_decode</span><span class="p">(</span>
        <span class="bp">self</span><span class="p">,</span> <span class="n">emissions</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">FloatTensor</span><span class="p">,</span> <span class="n">mask</span><span class="p">:</span> <span class="n">torch</span><span class="o">.</span><span class="n">ByteTensor</span>
    <span class="p">)</span> <span class="o">-&gt;</span> <span class="n">List</span><span class="p">[</span><span class="n">List</span><span class="p">[</span><span class="nb">int</span><span class="p">]]:</span>
        <span class="c1"># emissions: (seq_length, batch_size, num_tags)</span>
        <span class="c1"># mask: (seq_length, batch_size)</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">==</span> <span class="mi">3</span> <span class="ow">and</span> <span class="n">mask</span><span class="o">.</span><span class="n">dim</span><span class="p">()</span> <span class="o">==</span> <span class="mi">2</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">shape</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="n">mask</span><span class="o">.</span><span class="n">shape</span>
        <span class="k">assert</span> <span class="n">emissions</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">num_tags</span>
        <span class="k">assert</span> <span class="n">mask</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>

        <span class="n">seq_length</span><span class="p">,</span> <span class="n">batch_size</span> <span class="o">=</span> <span class="n">mask</span><span class="o">.</span><span class="n">shape</span>

        <span class="c1"># Start transition and first emission</span>
        <span class="c1"># shape: (batch_size, num_tags)</span>
        <span class="n">score</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start_transitions</span> <span class="o">+</span> <span class="n">emissions</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="n">history</span> <span class="o">=</span> <span class="p">[]</span>

        <span class="c1"># score is a tensor of size (batch_size, num_tags) where for every batch,</span>
        <span class="c1"># value at column j stores the score of the best tag sequence so far that ends</span>
        <span class="c1"># with tag j</span>
        <span class="c1"># history saves where the best tags candidate transitioned from; this is used</span>
        <span class="c1"># when we trace back the best tag sequence</span>

        <span class="c1"># Viterbi algorithm recursive case: we compute the score of the best tag sequence</span>
        <span class="c1"># for every possible next tag</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">seq_length</span><span class="p">):</span>
            <span class="c1"># Broadcast viterbi score for every possible next tag</span>
            <span class="c1"># shape: (batch_size, num_tags, 1)</span>
            <span class="n">broadcast_score</span> <span class="o">=</span> <span class="n">score</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

            <span class="c1"># Broadcast emission score for every possible current tag</span>
            <span class="c1"># shape: (batch_size, 1, num_tags)</span>
            <span class="n">broadcast_emission</span> <span class="o">=</span> <span class="n">emissions</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

            <span class="c1"># Compute the score tensor of size (batch_size, num_tags, num_tags) where</span>
            <span class="c1"># for each sample, entry at row i and column j stores the score of the best</span>
            <span class="c1"># tag sequence so far that ends with transitioning from tag i to tag j and emitting</span>
            <span class="c1"># shape: (batch_size, num_tags, num_tags)</span>
            <span class="n">next_score</span> <span class="o">=</span> <span class="n">broadcast_score</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">transitions</span> <span class="o">+</span> <span class="n">broadcast_emission</span>

            <span class="c1"># Find the maximum score over all possible current tag</span>
            <span class="c1"># shape: (batch_size, num_tags)</span>
            <span class="n">next_score</span><span class="p">,</span> <span class="n">indices</span> <span class="o">=</span> <span class="n">next_score</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

            <span class="c1"># Set score to the next score if this timestep is valid (mask == 1)</span>
            <span class="c1"># and save the index that produces the next score</span>
            <span class="c1"># shape: (batch_size, num_tags)</span>
            <span class="n">score</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">mask</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">.</span><span class="n">unsqueeze</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">next_score</span><span class="p">,</span> <span class="n">score</span><span class="p">)</span>
            <span class="n">history</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">indices</span><span class="p">)</span>

        <span class="c1"># End transition score</span>
        <span class="c1"># shape: (batch_size, num_tags)</span>
        <span class="n">score</span> <span class="o">+=</span> <span class="bp">self</span><span class="o">.</span><span class="n">end_transitions</span>

        <span class="c1"># Now, compute the best path for each sample</span>

        <span class="c1"># shape: (batch_size,)</span>
        <span class="n">seq_ends</span> <span class="o">=</span> <span class="n">mask</span><span class="o">.</span><span class="n">long</span><span class="p">()</span><span class="o">.</span><span class="n">sum</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="n">best_tags_list</span> <span class="o">=</span> <span class="p">[]</span>

        <span class="k">for</span> <span class="n">idx</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">batch_size</span><span class="p">):</span>
            <span class="c1"># Find the tag which maximizes the score at the last timestep; this is our best tag</span>
            <span class="c1"># for the last timestep</span>
            <span class="n">_</span><span class="p">,</span> <span class="n">best_last_tag</span> <span class="o">=</span> <span class="n">score</span><span class="p">[</span><span class="n">idx</span><span class="p">]</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">dim</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
            <span class="n">best_tags</span> <span class="o">=</span> <span class="p">[</span><span class="n">best_last_tag</span><span class="o">.</span><span class="n">item</span><span class="p">()]</span>

            <span class="c1"># We trace back where the best last tag comes from, append that to our best tag</span>
            <span class="c1"># sequence, and trace it back again, and so on</span>
            <span class="k">for</span> <span class="n">hist</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">history</span><span class="p">[:</span> <span class="n">seq_ends</span><span class="p">[</span><span class="n">idx</span><span class="p">]]):</span>
                <span class="n">best_last_tag</span> <span class="o">=</span> <span class="n">hist</span><span class="p">[</span><span class="n">idx</span><span class="p">][</span><span class="n">best_tags</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]]</span>
                <span class="n">best_tags</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">best_last_tag</span><span class="o">.</span><span class="n">item</span><span class="p">())</span>

            <span class="c1"># Reverse the order because we start from the last timestep</span>
            <span class="n">best_tags</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span>
            <span class="n">best_tags_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">best_tags</span><span class="p">)</span>

        <span class="k">return</span> <span class="n">best_tags_list</span></div>
</pre></div>

           </div>
           
          </div>
          <footer>
  

  <hr/>

  <div role="contentinfo">
    <p>

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>

  
  
    
   

</body>
</html>